package com.xhdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhdp.dto.Result;
import com.xhdp.dto.UserDTO;
import com.xhdp.entity.Blog;
import com.xhdp.entity.User;
import com.xhdp.mapper.BlogMapper;
import com.xhdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhdp.service.IUserService;
import com.xhdp.utils.SystemConstants;
import com.xhdp.utils.UserHolder;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.xhdp.utils.RedisConstants.BLOG_LIKED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaohe
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Autowired
    private IUserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 热帖查询
     * @param current
     * @return
     */
    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            this.queryBlogUser(blog);
            this.isLikedBlog(blog);
        });
        return Result.ok(records);
    }

    /**
     * 根据id查询博客详情
     * @param id
     * @return
     */
    @Override
    public Result queryBlogById(Long id) {
        //查询blog
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("博客不存在！");
        }
        //查询blog相关的用户信息
        queryBlogUser(blog);
        //查询用户是否点赞博客
        isLikedBlog(blog);
        //返回blog信息
        return Result.ok(blog);
    }

    /**
     * 点赞博客
     * @param id
     * @return
     */
    @Override
    public Result likeBlog(Long id) {
        //获取当前用户
        Long userId = UserHolder.getUser().getId();
        //判断当前用户是否已点赞
        String likedKey = BLOG_LIKED_KEY + id;
        Double score = stringRedisTemplate.opsForZSet().score(likedKey, userId.toString());
        if (score == null) {
            //如果未点赞，可以点赞
            //数据库点赞数 + 1
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
            if (isSuccess) {
                //保存用户到 Redis 的 sortedset 集合 zadd key value score
                stringRedisTemplate.opsForZSet().add(likedKey, userId.toString(), System.currentTimeMillis());
            }
        } else {
            //如果已点赞，取消点赞
            //数据库点赞数 - 1
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
            if (isSuccess) {
                //将用户从 Redis 的 set 集合中移除
                stringRedisTemplate.opsForZSet().remove(likedKey, userId.toString());
            }
        }
        return Result.ok();
    }

    /**
     * 查询点赞排行 top5
     * @param id
     * @return
     */
    @Override
    public Result queryBlogLikes(Long id) {
        String likedKey = BLOG_LIKED_KEY + id;
        //查询 top5 的点赞用户 zrange key 0 4
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(likedKey, 0, 4);
        if (top5 == null || top5.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        //解析用户id
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        String idsStr = StrUtil.join(",", ids);
        //根据id查询用户 WHERE id IN (id1, id2, ...) ORDER BY FIELD (id, id1, id2, ...)
        List<User> users = userService
                .query().in("id", ids).last("ORDER BY FIELD(id, " + idsStr + ")").list();
        //用户数据脱敏
        List<UserDTO> userDTOS = users.stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        //返回
        return Result.ok(userDTOS);
    }

    /**
     * 查询blog相关的用户信息
     * @param blog
     */
    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    /**
     * 查询用户是否点赞
     * @param blog
     */
    private void isLikedBlog(Blog blog) {
        //获取当前用户
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            //未登录，无需查询是否点赞
            return;
        }
        Long userId = user.getId();
        //判断当前用户是否已点赞
        String likedKey = BLOG_LIKED_KEY + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(likedKey, userId.toString());
        blog.setIsLike(score != null);
    }
}